﻿namespace com.crownpack.Extensions.SharePointExtensions
{
    using System.IO;

    using com.crownpack.Extensions.StringExtensions;

    using Microsoft.SharePoint;

    public static partial class SharePointExtensions
    {
        #region Methods

        public static SPDocumentLibrary AddContentType( this SPDocumentLibrary spDocumentLibrary, params SPContentType[ ] spContentTypes )
        {
            SPWeb spWeb = spDocumentLibrary.ParentWeb;
            if ( !spDocumentLibrary.ContentTypesEnabled )
            {
                spDocumentLibrary.ContentTypesEnabled = true;
                spDocumentLibrary.Update( );
            }
            int i = 0;
            foreach ( SPContentType o in spContentTypes )
                if ( !spWeb.ContentTypeExists( spDocumentLibrary, o ) )
                {
                    spDocumentLibrary.ContentTypes.Add( o );
                    i++;
                }
            if ( i > 0 )
                spDocumentLibrary.Update( );
            return spDocumentLibrary;
        }

        public static bool AddDocument( this SPDocumentLibrary spDocumentLibrary, Stream fileToUpload, string filename, string checkInComment )
        {
            SPWeb spWeb = spDocumentLibrary.ParentWeb;

            SPFolder spFolder = spWeb.Folders[ spDocumentLibrary.Title ];

            SPFile spFile = spFolder.Files.Add( filename, fileToUpload, true, checkInComment.SafeTrim( ), false );

            spFolder.Update( );

            return ( spFile == null ) ? false : true;
        }

        public static bool AddDocument( this SPDocumentLibrary spDocumentLibrary, string fileToUpload, string checkInComment )
        {
            SPWeb spWeb = spDocumentLibrary.ParentWeb;

            string filename = Path.GetFileName( fileToUpload );
            FileStream fileStream = File.OpenRead( fileToUpload );

            SPFolder spFolder = spWeb.Folders[ spDocumentLibrary.Title ];

            SPFile spFile = spFolder.Files.Add( filename, fileStream, true, checkInComment.SafeTrim( ), false );

            spFolder.Update( );

            return ( spFile == null ) ? false : true;
        }

        public static bool ContentTypeExists( this SPDocumentLibrary spDocumentLibrary, SPContentType spContentType )
        {
            foreach ( SPContentType o in spDocumentLibrary.ContentTypes )
                if ( o.Id.Equals( spContentType.Id ) )
                    return true;
            return false;
        }

        #endregion Methods
    }
}